const SerialPort = require('serialport')
const fs = require('fs')
const chalk = require('chalk');
const log = console.log
//读取配置文件
let config 
try {
  config = JSON.parse(fs.readFileSync('./config.json'))
} catch (e) {
  config = JSON.parse(fs.readFileSync(__dirname + '/config.json'))
}
//监控数据
const MonitorModel = require('./module/monitor')
const monitor = new MonitorModel(config)
//文件
const SerialFile = require('./module/file')
const file = new SerialFile(config.DEBUG)

const port = new SerialPort(config.port, {
  baudRate: config.baudRate,
  autoOpen: true
})

//端口占用就退出
port.on('error',()=>process.exit())
//接收端
port.on('data', function(data) {
  monitor.recive(data)
  //判断是否足够发送的数据量
  if(!monitor.lengthEqual())
    return
  log('数据接收: ' + monitor.recivedData)
  //校验
  validate()
});
setInterval(() => {
  monitor.timer -=50
  //判断时间是否到期
  if(monitor.timer<=0){
    validate()
    sendMsg()
  }
}, 50);
setInterval(() => {
  summary()
}, config.summary*1000);
//销毁前回调
process.on('SIGINT', function () {
  summary()
  process.exit();
});

//首次发送
sendMsg()

//发送串口内容
function sendMsg(){
  port.write(monitor.randomData(), function(err) {
    log("发送数据："+ monitor.sendData)
    if (err) {
      return log('错误信息: ', err.message)
    }
    monitor.restart()
    log(`这是发送的第${monitor.count}包`)
  })
}
//校验
function validate(){
  if(!monitor.haveRecived()){
    monitor.plus('lost')
    file.append('\n')
    file.append(`这是发送的第${monitor.count}包`)
    file.appendWithConsole(`这是丢失的第${monitor.lost}包`)
    return
  }
  if(monitor.recivedData != monitor.sendData){
    monitor.plus('err')
    file.append('\n')
    file.append(`这是发送的第${monitor.count}包`)
    file.appendWithConsole(`这是错误的第${monitor.err}包`)
    // file.append('数据接收: ' + monitor.recivedData)
    prtErr()
  }
}
function prtErr(){
  let c = ""
  let d = ""
  let cc = "" ,dd = ""
  for (let i = 0; i < monitor.sendData.length; i++) {
    const sch = monitor.sendData.charCodeAt(i).toString(16)
    const rch = monitor.recivedData.charCodeAt(i).toString(16)
    if(sch == rch){
      c += chalk.dim.blue(rch) + " "
      
    }else{
      c += chalk.dim.red(rch) + " "
    }
    d += chalk.dim.blue(sch) + " "

    cc += rch + " "
    dd += sch + " "
  }
  log("发送：",d)
  log("接收：",c)
  file.append("发送：" + dd)
  file.append("接收：" + cc)
}

function summary(){
  file.appendWithConsole(`共发出${monitor.count}包。`);
  file.appendWithConsole(`丢失${monitor.lost}包，丢包率${monitor.lostRate()}%。`);
  file.appendWithConsole(`错误${monitor.err}包，错误率${monitor.errorRate()}%。`);
}

